package au.com.handsunited.model.validators;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author arunda
 *
 */
public class EmailAddressValidator {

	private String emailAddresses;
	private final List<String> validEmailAddresses;
	private final List<String> invalidEmailAddresses;

	private static final String EMAIL_ADDRESS_DELIMITERS = ",;:|";

	private static Logger logger = LoggerFactory.getLogger(EmailAddressValidator.class);


	/**
	 *
	 */
	public EmailAddressValidator() {
		super();
		validEmailAddresses = new ArrayList<String>();
		invalidEmailAddresses = new ArrayList<String>();
	}

	/**
	 *
	 */
	public EmailAddressValidator(String emailAddresses) {
		this();
		this.emailAddresses = emailAddresses;
		validateEmailAddresses();
	}

	/**
	 *
	 */
	private void validateEmailAddresses() {
		List<String> emailAddressList = new ArrayList<String>();

		if (StringUtils.isNotBlank(emailAddresses)) {
			StringTokenizer tokenizer = new StringTokenizer(emailAddresses, EMAIL_ADDRESS_DELIMITERS);
			EmailValidator emailAddressValidator = EmailValidator.getInstance();

			while (tokenizer.hasMoreTokens()) {

				String emailAddress = tokenizer.nextToken();
				if (emailAddressValidator.isValid(emailAddress)) {
					validEmailAddresses.add(emailAddress);
				} else {
					invalidEmailAddresses.add(emailAddress);
				}
			}
		}
	}

	/**
	 * @return the validEmailAddresses
	 */
	public List<String> getValidEmailAddresses() {
		return validEmailAddresses;
	}


	/**
	 * @return the invalidEmailAddresses
	 */
	public List<String> getInvalidEmailAddresses() {
		return invalidEmailAddresses;
	}


	/**
	 * @return the emailAddresses
	 */
	public String getEmailAddresses() {
		return emailAddresses;
	}

	/**
	 *
	 * @param emailAddress
	 * @return
	 */
	public static boolean isValid(String emailAddress) {
		return EmailValidator.getInstance().isValid(emailAddress);
	}

}
